import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useAppStore } from '@/stores/appStore';
import { Cpu, Zap, Settings, CheckCircle, FileText, Database } from 'lucide-react';
import { OriginalDataDisplay } from '@/components/ui/OriginalDataDisplay';

interface ProofStep {
  id: string;
  name: string;
  description: string;
  status: 'pending' | 'processing' | 'completed';
  duration: number;
  icon: React.ReactNode;
  command?: string;
}

export function Stage2ProofGeneration() {
  const { zkProofData, experienceMode } = useAppStore();
  const [currentStep, setCurrentStep] = useState(0);
  const [isGenerating, setIsGenerating] = useState(false);
  const [generationProgress, setGenerationProgress] = useState(0);
  
  const proofSteps: ProofStep[] = [
    {
      id: 'circuit-compile',
      name: '电路编译',
      description: '编译 verifyAsset.circom 生成约束系统',
      status: 'pending',
      duration: 2000,
      icon: <Settings className="w-6 h-6" />,
      command: './circom/target/release/circom verifyAsset.circom --r1cs --wasm --sym -o build'
    },
    {
      id: 'trusted-setup',
      name: 'PLONK 可信设置',
      description: '生成证明密钥和验证密钥',
      status: 'pending',
      duration: 3000,
      icon: <Database className="w-6 h-6" />,
      command: 'snarkjs pks build/verifyAsset.r1cs pot20_final.ptau build/verifyAsset_final.zkey'
    },
    {
      id: 'proof-generate',
      name: '证明生成',
      description: '使用 PLONK 算法生成零知识证明',
      status: 'pending',
      duration: 4000,
      icon: <Zap className="w-6 h-6" />,
      command: 'snarkjs pkf input.json build/verifyAsset_js/verifyAsset.wasm build/verifyAsset_final.zkey proof.json public.json'
    },
    {
      id: 'verify-proof',
      name: '证明验证',
      description: '本地验证生成的证明',
      status: 'pending',
      duration: 1500,
      icon: <CheckCircle className="w-6 h-6" />,
      command: 'snarkjs plonk verify build/verifyAsset_final.zkey public.json proof.json'
    }
  ];
  
  const [steps, setSteps] = useState(proofSteps);
  
  useEffect(() => {
    if (experienceMode.autoplay) {
      const timer = setTimeout(() => {
        startProofGeneration();
      }, 2000);
      
      return () => clearTimeout(timer);
    }
  }, [experienceMode.autoplay]);
  
  const startProofGeneration = async () => {
    console.log('\n=== ⚡ STAGE 2: 开始PLONK证明生成 ===');
    console.log('步骤2.1: 检查是否已在生成中');
    
    if (isGenerating) {
      console.log('❌ 步骤2.1失败: 证明生成已在进行中');
      return;
    }
    
    console.log('步骤2.2: 初始化证明生成状态');
    setIsGenerating(true);
    setGenerationProgress(0);
    console.log('  - 生成状态: 已启动');
    console.log('  - 进度重置: 0%');
    console.log('  - 证明步骤总数:', steps.length);
    
    for (let i = 0; i < steps.length; i++) {
      const currentStepInfo = steps[i];
      console.log(`\n--- 步骤2.${i+3}: 开始执行 "${currentStepInfo.name}" ---`);
      console.log('  - 步骤ID:', currentStepInfo.id);
      console.log('  - 描述:', currentStepInfo.description);
      console.log('  - 预计耗时:', currentStepInfo.duration + 'ms');
      if (currentStepInfo.command) {
        console.log('  - 模拟命令:', currentStepInfo.command);
      }
      
      setCurrentStep(i);
      
      // Update step status to processing
      console.log('  - 更新步骤状态为: processing');
      setSteps(prev => prev.map((step, index) => ({
        ...step,
        status: index === i ? 'processing' : index < i ? 'completed' : 'pending'
      })));
      
      // Simulate step progress
      const stepDuration = currentStepInfo.duration;
      const progressInterval = stepDuration / 100;
      console.log('  - 开始模拟执行过程...');
      
      for (let progress = 0; progress <= 100; progress += 2) {
        setGenerationProgress(progress);
        await new Promise(resolve => setTimeout(resolve, progressInterval));
        
        // 每20%输出一次进度
        if (progress % 20 === 0) {
          console.log(`    进度: ${progress}%`);
        }
      }
      
      // Mark step as completed
      console.log('✅ 步骤执行完成，标记为completed');
      setSteps(prev => prev.map((step, index) => ({
        ...step,
        status: index <= i ? 'completed' : 'pending'
      })));
      
      console.log(`--- 步骤2.${i+3}: "${currentStepInfo.name}" 完成 ---`);
      await new Promise(resolve => setTimeout(resolve, 500));
    }
    
    console.log('\n步骤2.7: 证明生成流程完成');
    console.log('  - 设置生成状态: 完成');
    console.log('  - 当前步骤: 全部完成');
    
    setIsGenerating(false);
    setCurrentStep(steps.length);
    
    console.log('🎉 Stage2完成: PLONK零知识证明生成成功');
    console.log('=== ⚡ STAGE 2: 结束 ===\n');
  };
  
  const getStatusColor = (status: ProofStep['status']) => {
    switch (status) {
      case 'pending': return 'text-gray-400';
      case 'processing': return 'text-quantum-blue';
      case 'completed': return 'text-crypto-green';
      default: return 'text-gray-400';
    }
  };
  
  const getStatusBg = (status: ProofStep['status']) => {
    switch (status) {
      case 'pending': return 'bg-gray-700';
      case 'processing': return 'bg-quantum-blue/20 border-quantum-blue';
      case 'completed': return 'bg-crypto-green/20 border-crypto-green';
      default: return 'bg-gray-700';
    }
  };
  
  return (
    <div className="stage-container">
      <div className="max-w-6xl mx-auto">
        {/* Stage title */}
        <motion.div
          initial={{ opacity: 0, y: -50 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8 }}
          className="text-center mb-12"
        >
          <h1 className="text-5xl font-bold gradient-text mb-4">
            ⚡ PLONK 证明工厂
          </h1>
          <p className="text-xl text-gray-300">
            将您的秘密数据转换成零知识证明
          </p>
        </motion.div>
        
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
          {/* Left side - Process visualization */}
          <motion.div
            initial={{ opacity: 0, x: -100 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.4, duration: 0.8 }}
            className="space-y-6"
          >
            {/* Factory visualization */}
            <div className="floating-card">
              <h3 className="text-2xl font-semibold text-white mb-6 flex items-center">
                <Cpu className="mr-3 text-quantum-blue" size={28} />
                PLONK 算法引擎
              </h3>
              
              {/* Factory assembly line */}
              <div className="relative h-64 bg-slate-800 rounded-lg p-6 overflow-hidden">
                {/* Conveyor belt */}
                <div className="absolute bottom-8 left-0 right-0 h-4 bg-gray-600 rounded-full">
                  <motion.div
                    className="h-full bg-gradient-to-r from-quantum-blue to-crypto-green rounded-full"
                    animate={{ 
                      width: isGenerating ? `${generationProgress}%` : '0%' 
                    }}
                    transition={{ duration: 0.3 }}
                  />
                </div>
                
                {/* Factory machines */}
                <div className="grid grid-cols-4 gap-4 h-32">
                  {steps.map((step, index) => (
                    <motion.div
                      key={step.id}
                      className={`rounded-lg border-2 p-3 flex flex-col items-center justify-center text-center transition-all ${getStatusBg(step.status)}`}
                      animate={{
                        scale: currentStep === index && isGenerating ? [1, 1.1, 1] : 1,
                        boxShadow: step.status === 'processing' ? [
                          '0 0 0 rgba(59, 130, 246, 0)',
                          '0 0 20px rgba(59, 130, 246, 0.6)',
                          '0 0 0 rgba(59, 130, 246, 0)'
                        ] : '0 0 0 rgba(0, 0, 0, 0)'
                      }}
                      transition={{ 
                        scale: { duration: 1, repeat: step.status === 'processing' ? Infinity : 0 },
                        boxShadow: { duration: 2, repeat: step.status === 'processing' ? Infinity : 0 }
                      }}
                    >
                      <div className={`${getStatusColor(step.status)} mb-1`}>
                        {step.icon}
                      </div>
                      <span className={`text-xs font-medium ${getStatusColor(step.status)}`}>
                        {step.name}
                      </span>
                    </motion.div>
                  ))}
                </div>
                
                {/* Processing particles */}
                {isGenerating && (
                  <>
                    {Array.from({ length: 8 }, (_, i) => (
                      <motion.div
                        key={i}
                        className="absolute w-2 h-2 bg-quantum-blue rounded-full"
                        style={{
                          left: '10%',
                          top: '60%',
                        }}
                        animate={{
                          x: [0, 300],
                          opacity: [0, 1, 1, 0],
                        }}
                        transition={{
                          duration: 3,
                          delay: i * 0.3,
                          repeat: Infinity,
                        }}
                      />
                    ))}
                  </>
                )}
              </div>
              
              {/* Control panel */}
              <div className="mt-6">
                <motion.button
                  onClick={startProofGeneration}
                  disabled={isGenerating}
                  whileHover={{ scale: isGenerating ? 1 : 1.02 }}
                  whileTap={{ scale: isGenerating ? 1 : 0.98 }}
                  className={`w-full py-3 px-6 rounded-lg font-semibold transition-all ${
                    isGenerating 
                      ? 'bg-gray-700 text-gray-500 cursor-not-allowed'
                      : 'bg-quantum-blue hover:bg-blue-600 text-white'
                  }`}
                >
                  {isGenerating ? (
                    <span className="flex items-center justify-center">
                      <motion.div
                        animate={{ rotate: 360 }}
                        transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                        className="w-5 h-5 border-2 border-white border-t-transparent rounded-full mr-2"
                      />
                      正在生成证明... {generationProgress.toFixed(0)}%
                    </span>
                  ) : (
                    '🚀 启动证明生成'
                  )}
                </motion.button>
              </div>
            </div>
            
            {/* Input data display */}
            <div className="floating-card">
              <h3 className="text-lg font-semibold text-white mb-4">📥 输入数据</h3>
              <div className="bg-slate-800 rounded-lg p-4 font-mono text-sm">
                <div className="text-gray-300">
                  <div className="flex justify-between">
                    <span>preImage:</span>
                    <span className="text-green-400">{zkProofData?.input?.preImage || '888888'}</span>
                  </div>
                  <div className="flex justify-between mt-1">
                    <span>电路约束:</span>
                    <span className="text-blue-400">Poseidon Hash</span>
                  </div>
                </div>
              </div>
            </div>
          </motion.div>
          
          {/* Right side - Step details */}
          <motion.div
            initial={{ opacity: 0, x: 100 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.6, duration: 0.8 }}
            className="space-y-6"
          >
            {/* Process steps */}
            <div className="floating-card">
              <h3 className="text-2xl font-semibold text-white mb-6">📋 生成流程</h3>
              
              <div className="space-y-4">
                {steps.map((step) => (
                  <motion.div
                    key={step.id}
                    className={`p-4 rounded-lg border transition-all ${
                      step.status === 'processing' 
                        ? 'border-quantum-blue bg-quantum-blue/10' 
                        : step.status === 'completed'
                        ? 'border-crypto-green bg-crypto-green/10'
                        : 'border-gray-600 bg-gray-700/50'
                    }`}
                    animate={step.status === 'processing' ? { 
                      boxShadow: [
                        '0 0 0 rgba(59, 130, 246, 0)',
                        '0 0 20px rgba(59, 130, 246, 0.3)',
                        '0 0 0 rgba(59, 130, 246, 0)'
                      ]
                    } : {}}
                    transition={{ duration: 2, repeat: step.status === 'processing' ? Infinity : 0 }}
                  >
                    <div className="flex items-start space-x-3">
                      <div className={`${getStatusColor(step.status)} mt-1`}>
                        {step.status === 'processing' ? (
                          <motion.div
                            animate={{ rotate: 360 }}
                            transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                            className="w-6 h-6 border-2 border-current border-t-transparent rounded-full"
                          />
                        ) : step.status === 'completed' ? (
                          <CheckCircle className="w-6 h-6" />
                        ) : (
                          step.icon
                        )}
                      </div>
                      
                      <div className="flex-1">
                        <h4 className={`font-semibold ${getStatusColor(step.status)}`}>
                          {step.name}
                        </h4>
                        <p className="text-gray-300 text-sm mt-1">
                          {step.description}
                        </p>
                        
                        {/* Command display for developer mode */}
                        {experienceMode.showCode && step.command && (
                          <div className="mt-2 bg-slate-900 rounded p-2 text-xs font-mono text-gray-400">
                            $ {step.command}
                          </div>
                        )}
                        
                        {/* Progress bar for current step */}
                        {step.status === 'processing' && (
                          <div className="mt-2 w-full bg-gray-600 rounded-full h-1">
                            <motion.div
                              className="bg-quantum-blue h-1 rounded-full"
                              animate={{ width: `${generationProgress}%` }}
                              transition={{ duration: 0.3 }}
                            />
                          </div>
                        )}
                      </div>
                    </div>
                  </motion.div>
                ))}
              </div>
            </div>
            
            {/* Technical details for education mode */}
            {experienceMode.showTechDetails && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 1 }}
                className="bg-slate-800/50 rounded-lg p-4 border border-slate-700"
              >
                <h4 className="text-lg font-semibold text-white mb-3">🧠 PLONK 算法原理</h4>
                <div className="space-y-2 text-sm text-gray-300">
                  <p>• <strong>多项式承诺：</strong>使用 KZG 承诺方案确保证明简洁性</p>
                  <p>• <strong>置换论证：</strong>通过置换检查验证约束满足</p>
                  <p>• <strong>批量验证：</strong>支持多个证明的批量验证优化</p>
                  <p>• <strong>通用设置：</strong>一次可信设置支持任意电路大小</p>
                </div>
              </motion.div>
            )}
            
            {/* Output preview */}
            {currentStep >= steps.length && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="floating-card"
              >
                <h3 className="text-lg font-semibold text-white mb-4 flex items-center">
                  <FileText className="mr-2 text-crypto-green" size={20} />
                  🎉 生成完成
                </h3>
                <div className="space-y-3">
                  <div className="bg-slate-800 rounded p-3">
                    <div className="text-sm text-gray-300 mb-1">proof.json</div>
                    <div className="text-xs font-mono text-green-400">
                      ✓ PLONK证明已生成 (2.2KB)
                    </div>
                  </div>
                  <div className="bg-slate-800 rounded p-3">
                    <div className="text-sm text-gray-300 mb-1">public.json</div>
                    <div className="text-xs font-mono text-blue-400">
                      ✓ 公共信号已导出 (84B)
                    </div>
                  </div>
                </div>
                
                <motion.div
                  className="mt-4 text-center text-quantum-blue"
                  animate={{ y: [0, -10, 0] }}
                  transition={{ duration: 2, repeat: Infinity }}
                >
                  <span className="text-2xl">📦</span>
                  <p className="font-semibold">准备进行ABI编码...</p>
                </motion.div>
              </motion.div>
            )}
          </motion.div>
          
          {/* Original Data Display */}
          {currentStep >= proofSteps.length && (
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.5 }}
              className="mt-8"
            >
              <OriginalDataDisplay 
                title="生成证明的原始数据"
                compact={experienceMode.id === 'quick' || experienceMode.id === 'presentation'}
                showControls={experienceMode.showTechDetails || experienceMode.showCode}
              />
            </motion.div>
          )}
        </div>
      </div>
    </div>
  );
}